#include<iostream>
#include<string>
#include<pthread.h>
#include<unistd.h>
#include<mutex>//C++语言封装的锁

using namespace std;
class Ticket
{
private:
    int tickets = 1000;
    //pthread_mutex_t mtx;//原生线程库，系统级别
    std::mutex mymtx;  //C++语言封装的锁,使用这个不需要手动调用初始化
public:
    Ticket()
    {
        //pthread_mutex_init(&mtx, nullptr);
    }
    bool BuyTickets()
    {
        bool res = true;
        //static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;//第三种加锁方式，创建之后也不用进行初始化
        //pthread_mutex_lock(&mtx);
        mymtx.lock(); 
        if(tickets>0)
        {
            usleep(3000);
            cout<<"我是线程["<<pthread_self()<<"]，我抢到了票："<<tickets<<endl;
            tickets--;
        }
        else
        {
            cout<<"我是线程["<<pthread_self()<<"]，没有票了"<<tickets<<endl;
            res = false;
        }
        //pthread_mutex_unlock(&mtx);
        mymtx.unlock();

        return res;
    }
    ~Ticket()
    {
        //pthread_mutex_destroy(&mtx);
    }
};
void* ThreadRun(void* args)
{
    Ticket* t = (Ticket*)args;
    while(true)
    {
        if(!t->BuyTickets())//买不到票该进程就退出
        {
            break;
        }
    }
}
#define NUM 5
int main()
{
    Ticket* t1 = new Ticket();
    pthread_t tid[5];
    for(int i=0; i<NUM; i++)
    {
        pthread_create(tid+i, nullptr, ThreadRun, (void*)t1);
    }

    for(int i=0; i<NUM; i++)
    {
        pthread_join(tid[i], nullptr);//不关注退出信息，传nullptr
    }
    return 0;
}
